var express = require('express');
var router = express.Router();
let { resolve } = require('path')
const sha1 = require('sha1')


const { requestProcess } = require('../utils/requestProcess');
const { text } = require('../utils/sendMessage');
const { isFromWeichat } = require('../utils/assertFunctions');

function handleError(error) {
  console.log(error);
}

/* 

一 自己计算的signature 和微信传递过来的signature 一致
[timestamp,nonce,token]按字典排序, 并且组合在一起
1. 形成数组
2. sha1加密
*/
router.get('/', function (req, res, next) {

  if (isFromWeichat(req.query)) {
    res.send(echostr);
  } else {
    res.send("error");
  }

});

/**
 * 
 */
router.post('/', function (req, res, next) {

  if (isFromWeichat(req.query)) {

    requestProcess(req)
      .then(requestBodyStr => {
        text(requestBodyStr)
          .then(txt => {
            console.log("send message for index!");
            res.send(txt);
            res.end('');
          })
          .catch(handleError);
      }).catch(handleError);
  }
  else
    res.end('');

});




module.exports = router;
